<template>
  <el-dialog
    :close-on-click-modal="false"
    v-model="visible"
    :title="title || (id ? '修改应用' : '新增应用')"
    @close="resetForm"
    width="60%"
  >
    <el-form
      v-loading="editLoading"
      :disabled="title ? true : false"
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
    >
      <div class="px-4">
        <el-form-item prop="name" label="应用名称">
          <el-input v-model="formData.name" placeholder="请输入应用名称" maxlength="50" />
        </el-form-item>
        <el-form-item prop="appIconUrl" label="应用图标">
          <el-upload
            :disabled="title ? true : false"
            accept=".png,.jpeg,.jpg,"
            class="avatar-uploader"
            :show-file-list="false"
            :http-request="events.handleUploadFile"
            :before-remove="events.handleRemoveFile"
            :on-preview="events.handleDownloadFile"
            :on-exceed="events.handleMoreFile"
          >
            <img v-if="imgFile.url" :src="imgFile.url" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item prop="oauthRedirectUrl" label="授权回调地址">
          <el-input v-model="formData.oauthRedirectUrl" placeholder="请输入授权回调地址" maxlength="255" />
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button v-if="!title" type="primary" @click="handleCreate" :loading="submitBtnLoading">确认</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { uploadFile, addAppManager, appManagerInfo, updateAppManager } from '@/api/system/app'
import { Plus } from '@element-plus/icons-vue'
const baseurl = import.meta.env.VITE_API_DOMAIN
const props = defineProps({
  id: {
    type: String,
    default: ''
  },
  visible: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: ''
  }
})
const emit = defineEmits(['update:visible', 'create', 'update'])
const formRef = ref(null)
const formData = reactive({
  name: '',
  appIconUrl: '',
  oauthRedirectUrl: ''
})
const imgFile = ref('')
const formRules = reactive({
  name: [{ required: true, trigger: 'blur', message: '请输入应用名称' }],
  appIconUrl: [{ required: true, trigger: 'blur', message: '请选择应用图标' }],
  oauthRedirectUrl: [{ required: true, trigger: 'blur', message: '请输入授权回调地址' }]
})
const handleCreate = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      submitBtnLoading.value = true
      if (!props.id) {
        addAppManager(formData)
          .then(() => {
            ElMessage.success('新增成功')
            emit('addSuccess')
          })
          .finally(() => {
            submitBtnLoading.value = false
          })
      } else {
        updateAppManager(formData)
          .then(() => {
            ElMessage.success('修改成功')
            emit('addSuccess')
          })
          .finally(() => {
            submitBtnLoading.value = false
          })
      }
    } else {
      return false
    }
  })
}
const resetForm = () => {
  delete formData.id
  emit('update:visible')
  imgFile.value = ''
  formRef.value.resetFields()
}
const submitBtnLoading = ref(false)
const editLoading = ref(false)
const events = {
  handleUploadFile({ file, onSuccess, onError }) {
    let data = new FormData()
    data.set('file', file)
    uploadFile(data)
      .then((res) => {
        if (res.code === 200) {
          ElMessage.success('上传成功')
          imgFile.value = {
            url: res.data.absolutePath
          }
          formData.appIconUrl = res.data.absolutePath
          onSuccess()
        } else {
          ElMessage.error('上传失败')
          onError()
        }
      })
      .catch((e) => {
        ElMessage.error('上传失败')
        onError()
      })
  },
  async handleRemoveFile() {
    if (props.params.dialogType === 'add') {
      await deleteFile(imgFile.value[0].name)
      ElMessage.success('删除成功')
    }
    if (props.params.dialogType === 'check') {
      await deleteFileById(imgFile.value[0].id)
      ElMessage.success('删除成功')
    }
  },
  handleDownloadFile({ url, name }) {
    const x = new XMLHttpRequest()
    x.open('GET', url, true)
    x.responseType = 'blob'
    x.onload = () => {
      const url = window.URL.createObjectURL(x.response)
      const a = document.createElement('a')
      a.href = url
      a.download = name
      a.click()
    }
    x.send()
  },
  handleMoreFile() {
    ElMessage.warning('只能上传一个文件!上传新文件前请先删除旧文件')
  }
}
watch(
  () => props.visible,
  async (newValue, oldValue) => {
    if (newValue) {
      const { id } = props
      if (id) {
        editLoading.value = true
        const { data } = await appManagerInfo(id)
        Object.assign(formData, data)
        if (formData.appIconUrl)
          imgFile.value = {
            url: formData.appIconUrl
          }
        editLoading.value = false
      }
    }
  }
)
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
